package org.light4admin.modules.system.controller;

import org.apache.commons.lang.StringUtils;
import org.light4admin.common.Constants;
import org.light4admin.common.aop.auth.PreAuthorize;
import org.light4admin.common.base.Response;
import org.light4admin.modules.system.domain.SysMenu;
import org.light4admin.modules.system.domain.vo.RouterVo;
import org.light4admin.modules.system.domain.vo.TreeSelect;
import org.light4admin.modules.system.service.ISysMenuService;
import org.light4admin.modules.system.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 菜单信息
 *
 * @author light4admin
 */
@RestController
@RequestMapping("/menu")
public class SysMenuController {
    @Autowired
    private ISysMenuService menuService;

    /**
     * 获取菜单列表
     */
    @PreAuthorize(hasPermi = "system:menu:list")
    @GetMapping("/list")
    public Response<List<SysMenu>> list(SysMenu menu) {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuList(menu, userId);
        return Response.success(menus);
    }

    /**
     * 根据菜单编号获取详细信息
     */
    @PreAuthorize(hasPermi = "system:menu:query")
    @GetMapping(value = "/{menuId}")
    public Response<SysMenu> getInfo(@PathVariable Long menuId) {
        return Response.success(menuService.selectMenuById(menuId));
    }

    /**
     * 获取菜单下拉树列表
     */
    @GetMapping("/treeselect")
    public Response<List<TreeSelect>> treeselect(SysMenu menu) {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuList(menu, userId);
        return Response.success(menuService.buildMenuTreeSelect(menus));
    }

    /**
     * 加载对应角色菜单列表树
     */
    @GetMapping(value = "/roleMenuTreeselect/{roleId}")
    public Response<Map<String, Object>> roleMenuTreeselect(@PathVariable("roleId") Long roleId) {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuList(userId);
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("checkedKeys", menuService.selectMenuListByRoleId(roleId));
        dataMap.put("menus", menuService.buildMenuTreeSelect(menus));
        return Response.success(dataMap);
    }

    /**
     * 新增菜单
     */
    @PreAuthorize(hasPermi = "system:menu:add")
//    @Log(title = "菜单管理", businessType = BusinessType.INSERT)
    @PostMapping
    public Response add(@Validated @RequestBody SysMenu menu) {
        if (Constants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) {
            return Response.failed("新增菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        } else if (Constants.YES_FRAME.equals(menu.getIsFrame())
                && !StringUtils.startsWithAny(menu.getPath(), new String[]{Constants.HTTP, Constants.HTTPS})) {
            return Response.failed("新增菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        menu.setCreateBy(SecurityUtils.getUsername());

        menuService.insertMenu(menu);
        return Response.success();
    }

    /**
     * 修改菜单
     */
    @PreAuthorize(hasPermi = "system:menu:edit")
//    @Log(title = "菜单管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public Response edit(@Validated @RequestBody SysMenu menu) {
        if (Constants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) {
            return Response.failed("修改菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        } else if (Constants.YES_FRAME.equals(menu.getIsFrame())
                && !StringUtils.startsWithAny(menu.getPath(), new String[]{Constants.HTTP, Constants.HTTPS})) {
            return Response.failed("修改菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        } else if (menu.getMenuId().equals(menu.getParentId())) {
            return Response.failed("修改菜单'" + menu.getMenuName() + "'失败，上级菜单不能选择自己");
        }
        menu.setUpdateBy(SecurityUtils.getUsername());

        menuService.updateMenu(menu);
        return Response.success();
    }

    /**
     * 删除菜单
     */
    @PreAuthorize(hasPermi = "system:menu:remove")
//    @Log(title = "菜单管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{menuId}")
    public Response remove(@PathVariable("menuId") Long menuId) {
        if (menuService.hasChildByMenuId(menuId)) {
            return Response.failed("存在子菜单,不允许删除");
        }
        if (menuService.checkMenuExistRole(menuId)) {
            return Response.failed("菜单已分配,不允许删除");
        }

        menuService.deleteMenuById(menuId);
        return Response.success();
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public Response<List<RouterVo>> getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return Response.success(menuService.buildMenus(menus));
    }
}
